import { reactive } from 'vue';
import SpuApi from '@/sheep/api/product/spu';

export const useScrollData = (options) => {
  const data = reactive([]);
  const defaultProps = {
    getApi: undefined,
    params: {},
    page: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    hasMore: true,
    isLoading: false,
  };
  const loadMoreData = reactive(Object.assign(defaultProps, options));

  const loadMore = async () => {
    console.log('子组件到底了', loadMoreData);
    if (!loadMoreData.hasMore || loadMoreData.getApi === undefined || loadMoreData.isLoading) {
      return;
    }
    loadMoreData.isLoading = true;
    const params = { ...loadMoreData.page, ...loadMoreData.params };
    const response = await loadMoreData.getApi(params);
    if (response.code === 0) {
      loadMoreData.hasMore = response.data.total > loadMoreData.page.pageNo * loadMoreData.page.pageSize;
      loadMoreData.page.pageNo++;
      loadMoreData.total = response.data.total;
      data.push(...response.data.list);
      loadMoreData.isLoading = false;
    }
  };

  const init = (option, clearData = false) => {
    const _option = {
      page: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      hasMore: true,
      isLoading: false,
    };
    Object.assign(loadMoreData, _option, option);
    if (clearData) {
      data.length = 0;
    }
  };

  return {
    loadMore,
    data,
    loadMoreData,
    init,
  };
};
